package com.weipai.education.service.impl;

import com.weipai.education.config.interceptor.LoginHandlerInterceptor;
import com.weipai.education.dao.RoleDao;
import com.weipai.education.dao.UserCategoryDao;
import com.weipai.education.dao.UserDao;
import com.weipai.education.enums.RetCode;
import com.weipai.education.enums.SourceStatus;
import com.weipai.education.enums.UserStatus;
import com.weipai.education.enums.UserType;
import com.weipai.education.model.Role;
import com.weipai.education.model.User;
import com.weipai.education.model.UserCategory;
import com.weipai.education.model.api.Response;
import com.weipai.education.service.LoginService;
import com.weipai.education.shiro.AppCacheDao;
import com.weipai.education.utils.PasswordHelper;
import com.weipai.education.utils.PropUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: 曹朋飞
 * @Date: 2018/12/12 10:58
 */
@Service
public class LoginServiceImpl implements LoginService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static int TIME_OUT = 3600 * 24 * 30;
    
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserCategoryDao userCategoryDao;
    @Autowired
    private LoginHandlerInterceptor loginHandlerInterceptor;
    @Autowired
    private AppCacheDao appCacheDao;
    
    @Override
    public Response login(String mobile, String password) {
        Response response = new Response();
        User user = userDao.getUserByMobile(mobile);
        if(user!=null){
            if(user.getIsAudit() == UserStatus.NO_AUDIT.getType()){
                response.setCode(RetCode.USER_NO_AUDIT);
                return response;
            }else if(user.getIsAudit() == UserStatus.REFUSE.getType()){
                response.setCode(RetCode.USER_REFUSE);
                return response;
            }else if(user.getStatus() == UserStatus.BLOCK_UP.getType()){
                response.setCode(RetCode.BLOCK_UP);
                return response;
            }else if(user.getType() != UserType.HQ_USER.getType()){
                if(user.getFlag().equals(0)){
                    response.setCode(RetCode.NO_USER);
                    return response;
                }
            }
        }
        if(user==null){
            response.setCode(RetCode.NO_USER);
            return response;
        }
        
        int type = loginHandlerInterceptor.getUserType();
        logger.info("into login username:{} type: {}", mobile, type);
        
        UsernamePasswordToken token = new UsernamePasswordToken(mobile, password);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            if (SourceStatus.MOVE.getType() == type) {
                //int expire = (int) (System.currentTimeMillis() / 1000 + TIME_OUT);
                int expire = (int) (System.currentTimeMillis() / 1000 + TIME_OUT);
                String authToken = PasswordHelper.generateToken(mobile, expire, PropUtils.getString("system.secretKey"));
                appCacheDao.save(authToken, user);
                response.put(LoginHandlerInterceptor.AUTH_TOKEN_HEADER, authToken);
                
                if(null != user.getUserCateId()){
                    UserCategory userCategory = userCategoryDao.selectByPrimaryKey(user.getUserCateId().toString());
                    response.put("userCateName", userCategory);
                }
                response.put("user", user);
            } else {
                Session session = subject.getSession();

                Role role = roleDao.getRoleById(user.getRoleId());
                if(null!=role){
                    response.put("roleName", role.getRoleName());
                }else{
                    logger.info("no user roleId:{}", user.getNickname());
                }
                session.setAttribute("loginUser", user);
                
                response.put("user", user);
            }
            response.setCode(RetCode.SUCCESS);
        } catch (IncorrectCredentialsException e) {
            logger.error("login error = {}", e.getMessage());
            //密码错误
            response.setCode(RetCode.PWD_ERROR);
        } catch (AuthenticationException e) {
            response.setCode(RetCode.LOGIN_FAIL);
            logger.error("login error = {}", e.getMessage());
        } catch (Exception e) {
            logger.error("login error = {}", e.getMessage());
            response.setCode(RetCode.LOGIN_FAIL);
        }
        return response;
    }

    @Override
    public Response loginOut() {
        Response response = new Response();
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        response.setCode(RetCode.SUCCESS);
        return response;
    }
}
